package com.example.service;

import com.example.common.Result;
import com.example.dto.UserDTO;
import com.example.entity.Dept;
import com.example.entity.UserEntity;
import com.example.mapper.DeptMapper;
import com.example.mapper.UserMapper;
import com.example.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;


    public UserEntity dtoToEntity(UserDTO userDTO) {
        if (userDTO == null) {
            return null;
        }
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userDTO, userEntity, "birthday");
        //  Birthday 空字符串，表示清空
        if (Objects.equals(userDTO.getBirthday(), "")) {
            userEntity.setBirthdayIsNull(true);
        } else if (userDTO.getBirthday() != null) {
            userEntity.setBirthday(LocalDate.parse(userDTO.getBirthday()));
        }
        return userEntity;
    }

    public UserVO entityToVo(UserEntity userEntity) {
        if (userEntity == null) {
            return null;
        }
        UserVO userVo = new UserVO();
        BeanUtils.copyProperties(userEntity, userVo);
        return userVo;
    }

    public void insertOne(UserDTO userDTO) {
        UserEntity userEntity = dtoToEntity(userDTO);
        LocalDateTime localDateTime = LocalDateTime.now();
        userEntity.setCreateTime(localDateTime);
        userEntity.setUpdateTime(localDateTime);
        userEntity.setNickname("新用户");
        List<UserEntity> userList = List.of(userEntity);
        userMapper.insertMany(userList);
    }

    public void updateMany(List<Integer> ids, UserDTO userDTO) {
        UserEntity userEntity = dtoToEntity(userDTO);
        LocalDateTime localDateTime = LocalDateTime.now();
        userEntity.setUpdateTime(localDateTime);
        userMapper.updateMany(ids, userEntity);
    }

    public UserVO login(UserDTO userDTO) {
        UserEntity userEntity = dtoToEntity(userDTO);
        UserEntity userResult = userMapper.login(userEntity);
        return entityToVo(userResult);
    }
}
